#!BPY
 
"""
Name: 'EQ2 File Format (.draw)...'
Blender: 242
Group: 'Import'
Tooltip: 'Load a EQ2 File, Shift: batch import all dir.'
"""

__author__= "Andrew Fenn"
__url__= ["http://code.google.com/p/openzone2/"]
__version__= "0.1"

__bpydoc__= """\
This script imports an EQ2 draw file into Blender.

Usage:
Run this script from "File->Import" menu and then load the desired EQ2 file.
"""

#   OpenZone2, Everquest 2 data editor
#   Copyright (C) 2008  Andrew Fenn
#    
#   OpenZone2 is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   OpenZone2 is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with OpenZone2.  If not, see <http://www.gnu.org/licenses/>.

import Blender
import array
import struct

try:		import os
except:		os= False

def getEQ2FileType(mesh):
        name = ""
        char = " "
        while ord(char) != 2:
           char = mesh.read(1)
           if ord(char) != 2:
              name += char
        return name

def getEQ2RenderMesh(eq2file, mesh):

		# Get Version
		version = struct.unpack("=H",eq2file.read(2))[0]
		print "version: "+str(version)

		# Get flags
		flags = struct.unpack("=L",eq2file.read(4))[0]
		print "flags: "+str(flags)

		# Get vertices
		vertlength = struct.unpack("=L",eq2file.read(4))[0]
		print "Vert Length: "+str(vertlength)

		vertList = []
		for i in range(0, vertlength):
			 temp = []
			 temp.append(struct.unpack("=f",eq2file.read(4))[0])
			 temp.append(struct.unpack("=f",eq2file.read(4))[0])
			 temp.append(struct.unpack("=f",eq2file.read(4))[0])
			 vertList.append(temp)

		# Get Normals
		normallength = struct.unpack("=L",eq2file.read(4))[0]
		print "Normal Length: "+str(normallength)

		for i in range(0, normallength):
			 x = struct.unpack("=f",eq2file.read(4))[0]
			 y = struct.unpack("=f",eq2file.read(4))[0]
			 z = struct.unpack("=f",eq2file.read(4))[0]
			 # TODO: Add normals ?

		# Get texture coords
		length = 8
		if version >= 15:
			length = 5

		for i in range(0, length):
			texlength = struct.unpack("=L",eq2file.read(4))[0]
			print "  - Texture "+str(i)+" length: "+str(texlength)

			for j in range(0, texlength*2):
			   x = struct.unpack("=f",eq2file.read(4))[0]

		# Get Vertex indices
		length = struct.unpack("=L",eq2file.read(4))[0]
		vertIndice = []
		print "Vertice Indice Length: "+str(length)
		for i in range(0, length):
			  vertIndice.append(struct.unpack("=H",eq2file.read(2))[0])
					
		length = struct.unpack("=L",eq2file.read(4))[0]
		print "Submesh length: "+str(length)

		submeshlist = []        
		for i in range(0, length):
			  PrimType = struct.unpack("=L",eq2file.read(4))[0]
			  StartingVertex = struct.unpack("=L",eq2file.read(4))[0]
			  VertexCount = struct.unpack("=L",eq2file.read(4))[0]
			  StartingIndex = struct.unpack("=L",eq2file.read(4))[0]
			  PrimitiveCount = struct.unpack("=L",eq2file.read(4))[0]
				
			  print " -- Submesh " + str(i) + ": "
			  print str(PrimType) + " - " + str(StartingVertex) + " - " + str(VertexCount) + " - " + str(StartingIndex) + " - " + str(PrimitiveCount)

			  for i2 in range(StartingVertex, StartingVertex+VertexCount):
				mesh.verts.extend([vertList[i2]])
		 
		faceVertList = []
		for j in range(StartingIndex, PrimitiveCount*3):
		  faceVertList.append(mesh.verts[vertIndice[j]])
		  if len(faceVertList) > PrimType:
			 faceList.append(faceVertList)
			 faceVertList = []

		#mesh.faces.extend(faceList)

		# Get Face normals?
		length = struct.unpack("=L",eq2file.read(4))[0]
		print "Face Normal Length: "+str(length)

		for i in range(0, length):
			   x = struct.unpack("=L",eq2file.read(4))[0]
			   y = struct.unpack("=L",eq2file.read(4))[0]
			   z = struct.unpack("=L",eq2file.read(4))[0]
			   print str(x) +"-"+ str(y) + "-" + str(z)
		# print eq2file.tell()

		# Get Edge count?
		length = struct.unpack("=L",eq2file.read(4))[0]
		print "Edge Count Length: "+str(length)
		for i in range(0, length*3):
			   eq2file.read(4)
			   
		# Get tangent basis
		length = struct.unpack("=L",eq2file.read(4))[0]
		print "Tangent Basis Length: "+str(length)
		for i in range(0, length):
			   eq2file.read(4)

		# Get bone names?
		length = struct.unpack("=L",eq2file.read(4))[0]
		print "Bone count: "+str(length)
		for i in range(0, length):
			   eq2file.read(2)

		# Get bone index?
		length = struct.unpack("=L",eq2file.read(4))[0]
		print "Bone index count: "+str(length)
		for i in range(0, length):
			   eq2file.read(1)

		# Get bone weight
		length = struct.unpack("=L",eq2file.read(4))[0]
		print "Bone weight count: "+str(length)
		for i in range(0, length):
			   eq2file.read(1)

		# Get autodrop index?
		length = struct.unpack("=L",eq2file.read(4))[0]
		print "Autodrop index count: "+str(length)
		for i in range(0, length):
			   eq2file.read(2)

		# Get unknown
		length = struct.unpack("=H",eq2file.read(2))[0]
		print "Unknown var Length: "+str(length)
		for i in range(0, length):
			   eq2file.read(1)

		# Get shaders
		length = struct.unpack("=L",eq2file.read(4))[0]
		print "Material Count: "+str(length)

		shader = ""
		for i in range(0, length):
			   namelen = struct.unpack("=H",eq2file.read(2))[0]
			   shader = eq2file.read(namelen)
			   print shader
		
		return mesh

        
def import_eq2(path):

        Blender.Window.WaitCursor(1)
        
        editmode = Blender.Window.EditMode()    # are we in edit mode?  If so ...
        if editmode: Blender.Window.EditMode(0) # leave edit mode before getting the mesh

        
        name = path.split('\\')[-1].split('/')[-1]
        mesh = Blender.Mesh.New( name ) # create a new mesh
        # parse the file
        eq2file = open(path, 'rb')
        filetype = getEQ2FileType(eq2file)

        if filetype.lstrip() == 'VeRenderMesh':
			mesh = getEQ2RenderMesh(eq2file, mesh)
			scn = Blender.Scene.GetCurrent()
			ob = scn.objects.new(mesh, name)  
        else:
            eq2file.close()
            print "Error: Wrong filetype"
            return
        
        eq2file.close()
        

        Blender.Window.WaitCursor(0)
        Blender.Window.RedrawAll()
        
        if editmode: Blender.Window.EditMode(1)  # optional, just being nice


Blender.Window.FileSelector(import_eq2, 'Import')
